import { IconButton, Tooltip } from '@mui/material'
import { Copy, CopyCheck } from 'lucide-react'
import { useEffect, useState } from 'react'

export const CopyButton = ({ text, size }: { text: string; size: number }) => {
	const [copied, setCopied] = useState<boolean>(false)

	const handleClick = () => {
		navigator.clipboard.writeText(text).then(r => setCopied(true))
	}

	useEffect(() => {
		if (copied) {
			const timeout = setTimeout(() => {
				setCopied(false)
			}, 3000)
			return () => clearTimeout(timeout)
		}
	}, [copied])

	return (
		<Tooltip
			title={copied ? 'Скопировано!' : 'Скопировать'}
			arrow
			slotProps={{
				popper: {
					modifiers: [
						{
							name: 'offset',
							options: {
								offset: [0, -8]
							}
						}
					]
				}
			}}
		>
			<IconButton
				disabled={copied}
				onClick={handleClick}
				size={'small'}
			>
				{copied ? <CopyCheck size={size} /> : <Copy size={size} />}
			</IconButton>
		</Tooltip>
	)
}
